<template>
  <!-- 凭证预览 -->
  <div class="jourDialog" v-if="isShow" :class="animClass">
    <div class="mask"></div>
    <div class="jourContent">
      <!-- 左侧列表 -->
      <div class="leftCont">
        <div class="loadBoxText" v-if="uploadLoading">{{ uploadText }}</div>
        <div class="loadBoxDiv" v-loading="uploadLoading">
          <div class="topNav">
            <span>{{ currentPage + 1 }} / {{ pictureData.length || 0 }}</span>
            <el-upload v-if="layoutFaly.includes('upload')" class="uploadDemo" :file-list="[]" action="#"
              :show-file-list="false" :http-request="() => { }" :on-change="addAllChangeImg" value-format="timestamp"
              multiple accept=".jpg, .jpeg, .png, .gif, .bmp, .JPG, .JPEG, .PBG, .GIF, .BMP" :auto-upload="false">
              <template v-if="!(imageList && imageList.length)" #trigger>
                <div class="uploadImg">
                  <upload theme="filled" size="21" fill="#fff" />
                  <span>上传</span>
                </div>
              </template>
            </el-upload>
          </div>
          <div class="imageBox scrollbar" id="imgList">
            <div class="imageList" v-if="pictureData.length">
              <div class="imageItem" v-for="(item, index) in pictureData" :key="index"
                :class="{ isActive: index == currentPage }" @click="selectCurrent(index)" :id="'img' + index">
                <div class="imgIcon">
                  <el-image class="image" :src="item" fit="contain" />
                  <div class="delIcon" @click="delectPicture(index)" v-if="layoutFaly.includes('delect')">
                    <close theme="filled" size="14" fill="#fff" />
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="noPictureData">暂无信息</div>
          </div>
        </div>
      </div>
      <!-- 右侧内容列表 -->
      <div class="rightCont">
        <div class="headNav">
          <p>{{ pictureDataName }}</p>
          <div class="closeBtn" @click="clocePicture">
            <close theme="filled" size="24" fill="#fff" />
          </div>
        </div>

        <div class="headText" v-if="layoutFaly.includes('content')">
          <div class="time">2022-10-12 10:15:20</div>
          <div class="content line-2">
            今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上今天晚上吃什么今天晚上吃什么今天晚上吃什么今天晚上陈今天晚上吃什么今天晚上
          </div>
        </div>
        <div class="preview">
          <p class="show" v-show="scaleDisplay">{{ percentage + '%' }}</p>
          <div class="preBtn">
            <img @click="handleImg(-1)" src="@/assets/image/imageLeft.png" mode="" />
          </div>
          <div class="preCont" ref="preCont">
            <img v-if="pictureData.length > 0" v-drag ref="img" @mousewheel="rollImg" :style="{
              transform: 'rotateZ(' + rotationAngle + 'deg) scale(' + scaleAngle + ')',
            }" :src="pictureData[currentPage]" alt="" />
          </div>
          <div class="preBtn">
            <img @click="handleImg(1)" src="@/assets/image/imageRight.png" mode="" />
          </div>
        </div>
        <div class="operate">
          <div class="operBtn">
            <zoom-in theme="outline" size="30" @click="operationScaleAngle(1)" fill="#fff" />
            <zoom-out theme="outline" size="30" @click="operationScaleAngle(-1)" fill="#fff" />
            <to-bottom @click="downloadImg(pictureData[currentPage], '名字')" theme="filled" size="30" fill="#fff" />
            <undo @click="setRotation(-1)" theme="filled" size="30" fill="#fff" />
            <redo @click="setRotation(1)" theme="filled" size="30" fill="#fff" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    layout: {
      type: String,
      default: '',
    },
    pictureData: {
      type: Array,
    },
    pictureDataName: {
      type: String,
    },
  },
  watch: {
    show(newVal) {
      this.animClass = newVal ? 'enterActive' : 'leaveActive'
      this.isShow = newVal
      this.isAddVoucherImage = false
      this.uploadLoading = false
    },
    layout(newVal) {
      if (this.layout) {
        this.layoutFaly = newVal.replace(/\s*/g, '').split(',')
      }
    },
  },

  directives: {
    drag: {
      //必须以 vNameOfDirective 的形式来命名本地自定义指令，以使得它们可以直接在模板中使用。
      beforeMount: (el) => {
        // 在元素上做些操作
        let dragBox = el //获取当前元素
        dragBox.onmousedown = (e) => {
          e.preventDefault()
          //算出鼠标相对元素的位置
          let disX = e.clientX - dragBox.offsetLeft
          let disY = e.clientY - dragBox.offsetTop
          document.onmousemove = (e) => {
            //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            e.preventDefault()
            let left = e.clientX - disX
            let top = e.clientY - disY
            //移动当前元素
            dragBox.style.left = left + 'px'
            dragBox.style.top = top + 'px'
          }
          document.onmouseup = (e) => {
            e.preventDefault()
            //鼠标弹起来的时候不再移动
            document.onmousemove = null
            //预防鼠标弹起来后还会循环（即预防鼠标放上去的时候还会移动）
            document.onmouseup = null
          }
        }
      },
    },
  },
  data() {
    return {
      fileListArr: [],
      uploadText: '',
      fileArr2: [],
      timers: null,
      uploadLoading: false,
      // 判断打开凭证的过程中是否有成功上传过凭证，有的话关闭时刷新页面，没有不做任何操作
      isEditImage: false,
      layoutFaly: [],
      isShow: false,
      currentId: 1,
      animClass: '',
      timeOut: null,
      rotationAngle: 0,
      scaleAngle: 1,
      scaleDisplay: false,
      percentage: 100,
      currentPage: 0,
      fileInfo: '',
      imageList: [],
    }
  },
  mounted() {
    if (this.layout) {
      this.layoutFaly = this.layout.replace(/\s*/g, '').split(',')
    }
    this.isShow = this.show
    window.addEventListener('keydown', this.handleKeyDown);
  },
  methods: {
    // 关闭相册列表
    clocePicture() {
      this.animClass = 'leaveActive'
      setTimeout(() => {
        this.isShow = false
        this.$emit('close', {
          isShow: this.isShow,
          isEditImage: this.isEditImage,
        })
        this.isEditImage = false
      }, 500)
    },
    // 切换图片
    handleImg(type) {
      if (this.pictureData.length < 0) {
        return
      }
      if (type == 1) {
        // 上一张
        this.currentPage++
        if (this.currentPage >= this.pictureData.length) {
          this.currentPage = 0
        }
      } else {
        // 下一张
        this.currentPage--
        if (this.currentPage < 0) {
          this.currentPage = this.pictureData.length - 1
        }
      }
      this.$refs.img.style.left = 'auto'
      this.$refs.img.style.top = 'auto'
      this.scaleAngle = 1
      this.rotationAngle = 0
      this.linkScroll()
    },
    selectCurrent(index) {
      this.currentPage = index
      this.scaleAngle = 1
      this.rotationAngle = 0
      this.$refs.img.style.left = 'auto'
      this.$refs.img.style.top = 'auto'
    },

    // 旋转图片
    setRotation(ind) {
      if (!this.pictureData.length) return
      if (ind == 1) {
        this.rotationAngle = this.rotationAngle == 360 ? 0 : (this.rotationAngle += 90)
      } else {
        this.rotationAngle = this.rotationAngle == -360 ? 0 : (this.rotationAngle -= 90)
      }
    },

    //判断滚动方向
    rollImg(e) {
      this.operationScaleAngle(e.deltaY)
    },
    // 放大缩小
    operationScaleAngle(ind) {
      if (!this.pictureData.length) return
      if (this.timeOut !== null) {
        clearTimeout(this.timeOut)
        this.timeOut = null
      }
      this.scaleDisplay = true
      if (ind > 0) {
        this.scaleAngle += 0.1
      } else {
        this.scaleAngle = this.scaleAngle > 0.5 ? (this.scaleAngle -= 0.1) : 0.5
      }

      this.timeOut = setTimeout(() => {
        this.scaleDisplay = false
      }, 1000)
      this.percentage = (this.scaleAngle * 100).toFixed(0)
    },

    // 滚动左侧图片框到当前选中图片位置
    linkScroll() {
      let target = document.getElementById(`img${this.currentPage}`)
      let parent = document.getElementById('imgList')
      parent.scrollTop = target.offsetTop - parent.offsetTop
    },
    // 下载图片
    downloadImg(imgurl, name) {
      if (!this.pictureData.length) return
      let eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = imgurl
      eleLink.click()
      eleLink.remove()
      // let image = new Image()
      // 解决跨域 Canvas 污染问题
      // image.setAttribute('crossOrigin', 'anonymous')
      // image.onload = function () {
      //   let canvas = document.createElement('canvas')
      //   canvas.width = image.width
      //   canvas.height = image.height
      //   let context = canvas.getContext('2d')
      //   context.drawImage(image, 0, 0, image.width, image.height)
      //   let url = canvas.toDataURL('image/png') //得到图片的base64编码数据
      //   let a = document.createElement('a') // 生成一个a元素
      //   let event = new MouseEvent('click') // 创建一个单击事件
      //   a.download = name || 'qrcode.jpg' // 设置图片名称
      //   a.href = url // 将生成的URL设置为a.href属性
      //   a.dispatchEvent(event) // 触发a的单击事件
      // }
      // image.src = imgurl
    },
    delectPicture(index) {
      this.$emit('delectPicture', index)
      this.isEditImage = true
      // ElMessageBox.confirm('确定需要删除该凭证？', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {

      // })
    },

    // 上传图片
    addAllChangeImg(e) {
      this.uploadLoading = true
      this.fileArr2 = []
      let aaInd = 0
      this.fileListArr.push(e)
      this.uploadText = `正在上传 ${this.fileListArr.length}/${aaInd}`
      clearTimeout(this.timers)
      this.timers = setTimeout(() => {
        this.isEditImage = true
        this.timers = null
        this.uploadImageFun(this.fileListArr[aaInd], aaInd)

        // this.fileListArr.forEach((items, indexs) => {
        // this.uploadImage(items.raw)
        //   .then((res) => {
        //     aaInd += 1
        //     this.fileArr2.push(res.result)
        //     this.isEditImage = true
        //     if (this.fileListArr.length == aaInd) {
        //       this.$emit('addVoucherImage', this.fileArr2)
        //       this.fileListArr = []
        //       this.uploadLoading = false
        //     }
        //   })
        //   .catch((err) => {
        //     aaInd += 1
        //     if (this.fileListArr.length == aaInd) {
        //       this.$emit('addVoucherImage', this.fileArr2)
        //       this.fileListArr = []
        //       this.uploadLoading = false
        //     }
        //   })
        // })
      }, 1000)
    },
    // 递归同步上传照片
    uploadImageFun(file, ind) {
      let aaInd = ind
      this.uploadText = `正在上传 ${this.fileListArr.length}/${ind}`
      this.uploadImage(file.raw)
        .then((res) => {
          this.fileArr2.push(res.result)
          aaInd += 1
          if (this.fileListArr.length <= aaInd) {
            this.$emit('addVoucherImage', this.fileArr2)
            this.fileListArr = []
            this.uploadLoading = false
          } else {
            this.uploadImageFun(this.fileListArr[aaInd], aaInd)
          }
        })
        .catch((err) => {
          aaInd += 1
          if (this.fileListArr.length <= aaInd) {
            this.$emit('addVoucherImage', this.fileArr2)
            this.fileListArr = []
            this.uploadLoading = false
          } else {
            this.uploadImageFun(this.fileListArr[aaInd], aaInd)
          }
        })
    },
    handleKeyDown(event) {
      if (event.key == 'ArrowLeft') {
        this.handleImg(-1)
      } else if (event.key == 'ArrowRight') {
        this.handleImg(1)
      }
    }
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeyDown);
  },
}
</script>
<style lang="scss" scoped>
.jourDialog {
  opacity: 0;
  transform: scale3d(0, 0, 1);
  position: fixed;
  z-index: 99;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  -webkit-touch-callout: none;
  /*系统默认菜单被禁用*/
  -webkit-user-select: none;
  /*webkit浏览器*/
  -khtml-user-select: none;
  /*早期浏览器*/
  -moz-user-select: none;
  /*火狐*/
  -ms-user-select: none;
  /*IE10*/
  user-select: none;

  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.6);
  }

  .jourContent {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    display: flex;
    width: 100%;
    height: 100%;

    .leftCont {
      display: flex;
      flex-direction: column;
      background-color: #4d4d4d;
      height: 100%;
      width: 300px;

      .loadBoxText {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 30px;
        background: #fff;
      }

      .loadBoxDiv {
        display: flex;
        flex-direction: column;
        height: 100%;
        width: 300px;
      }

      .topNav {
        height: 74px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 18px;
        border-bottom: 1px solid #b6b6b6;
        font-size: 18px;

        span {
          color: #fff;
        }

        .uploadImg {
          display: flex;
          align-items: center;

          span {
            line-height: 1;
            margin-left: 3px;
          }
        }
      }

      .imageBox {
        flex: 1;
        height: 0;
        overflow-y: auto;
        overflow-x: hidden;
        margin: 20px 0 2px 0;

        .noPictureData {
          padding-top: 120px;
          font-size: 20px;
          color: #fff;
          text-align: center;
        }

        .imageList {
          width: 296px;
          padding: 0 15px;

          .imageItem {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 268px;
            height: 168px;
            margin-bottom: 16px;
            background-color: #6a6a6a;
            cursor: pointer;

            .imgIcon {
              position: relative;
              width: 248px;
              height: 148px;

              .image {
                width: 248px;
                height: 148px;
              }

              .delIcon {
                display: flex;
                align-items: center;
                justify-content: center;
                position: absolute;
                right: -6px;
                top: -6px;
                width: 26px;
                height: 26px;
                background: #4d4d4d;
                border-radius: 50%;
              }
            }
          }

          .isActive {
            border: 2px solid #0ccaff;
          }
        }
      }
    }

    .rightCont {
      flex: 1;
      width: 0;
      display: flex;
      flex-direction: column;

      .headNav {
        height: 64px;
        position: relative;

        p {
          text-align: center;
          color: #ffffff;
          font-size: 28px;
          padding-top: 18px;
        }

        span {
          text-align: center;
          color: #ffffff;
          font-size: 28px;
          padding: 18px 0;
          display: inline-block;
          width: 100%;
          text-align: center;
        }

        .closeBtn {
          position: absolute;
          right: 42px;
          top: 14px;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          width: 50px;
          height: 50px;
          border-radius: 50%;
          background: #4d4d4d;
        }
      }

      .headText {
        width: 100%;
        color: #fff;
        text-align: center;

        .title {
          font-size: 16px;
        }

        .content {
          height: 54px;
          font-size: 18px;
          padding: 0 126px;
        }
      }

      .preview {
        display: flex;
        flex: 1;
        justify-content: space-between;
        height: 0;
        padding: 30px 0 20px 0;
        position: relative;

        .show {
          position: absolute;
          top: 60px;
          left: 50%;
          line-height: 26px;
          border-radius: 2px;
          padding: 0 8px;
          transform: translateX(-50%);
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          z-index: 99;
        }

        .hint {
          position: absolute;
          top: 100px;
          left: 50%;
          line-height: 26px;
          border-radius: 2px;
          padding: 0 8px;
          transform: translateX(-50%);
          background-color: rgba(0, 0, 0, 0.5);
          color: #fff;
          z-index: 99;
        }

        .preBtn {
          display: flex;
          align-items: center;
          height: 100%;
          width: 120px;
          padding: 0 28px;
          font-size: 30px;
          color: #fff;

          img {
            cursor: pointer;
            width: 64px;
            height: 64px;
          }
        }

        .preCont {
          position: relative;
          // width: calc(100vh - 280px);
          width: 100%;
          height: 100%;
          overflow: hidden;
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            max-width: 100%;
            max-height: 100%;
            position: absolute;
            cursor: grab;

            // top: 0;
            // left: 0;
            // right: 0;
            // bottom: 0;
            &:active {
              cursor: grabbing;
            }
          }
        }
      }

      .operate {
        height: 100px;
        width: 100%;
        display: flex;
        align-items: flex-start;
        justify-content: center;
        z-index: 9;

        .operBtn {
          display: flex;
          justify-content: space-around;
          align-items: center;
          width: 322px;
          height: 80px;
          background: #4d4d4d;

          span {
            cursor: pointer;
          }
        }
      }
    }
  }
}

// .enterActive {
//   animation: none !important;
// }
// .leaveActive {
//   transition-duration: 0.15s !important;
//   animation: none !important;
// }

.enterActive {
  animation-duration: 0.4s;
  animation-name: animOpen;
  animation-timing-function: cubic-bezier(0.6, 0, 0.4, 1);
  animation-fill-mode: forwards;
}

.leaveActive {
  animation-duration: 0.4s;
  animation-name: animClose;
  animation-fill-mode: forwards;
}

@keyframes animOpen {
  0% {
    opacity: 0;
    transform: scale3d(0, 0, 1);
  }

  100% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }
}

@keyframes animClose {
  0% {
    opacity: 1;
    transform: scale3d(1, 1, 1);
  }

  100% {
    opacity: 0;
    transform: scale3d(0, 0, 1);
  }
}
</style>
